import { Component, ElementRef, ViewChild, inject } from '@angular/core';
import { SunshineNgZorroAntdModule } from '../ng-zorro-module';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { NzFormTooltipIcon } from 'ng-zorro-antd/form';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { LocalStorageService } from '../study/services/local-storage.service';
import { LOCAL_KEY_PERMISSION } from '../study/services/ServiceConstant';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [SunshineNgZorroAntdModule],
  templateUrl: './login.component.html',
  styleUrl: './login.component.css'
})
export class LoginComponent {
  @ViewChild('verifyCode') verifyCode?: ElementRef;


  underlineToHump = (str: string): string => {
    return str.replace(/\-(\w)/g, (_, letter: string) => {
      return letter.toUpperCase()
    })
  }

  /**
   * 刷新雁阵吗
   */
  refreshCode() {
    this.verifyCode!.nativeElement.src = '/wstro/admin/captcha.jpg?t' + new Date().getTime();
  }

  validateForm!: FormGroup;
  captchaTooltipIcon: NzFormTooltipIcon = {
    type: 'info-circle',
    theme: 'twotone'
  };
  nzSm: number = 6;
  http: HttpClient = inject(HttpClient);

  router: Router = inject(Router);
  storeService: LocalStorageService = inject(LocalStorageService);
  private notification: NzNotificationService = inject(NzNotificationService);

  submitForm(): void {
    console.log(this.validateForm.value)
    if (this.validateForm.valid) {
      const httpOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json'
        })
      };

      this.http.post('http://localhost:4200/wstro/admin/sys/login2', JSON.stringify(this.validateForm.value), httpOptions).subscribe((res: any) => {
        console.log(res)
        if (res.code == 0) {
          this.http.get('http://localhost:4200/wstro/currentUser/perms').subscribe((result: any) => {
            console.log(result)
            this.storeService.set(LOCAL_KEY_PERMISSION, result.list)
          })
          this.router.navigateByUrl("/index").then(r => { console.log(r) })
        }
        else {
          this.notification.create(
            'error',
            '',
            res.msg
          );
          Object.values(this.validateForm.controls).forEach(control => {

            control.markAsDirty();
            control.updateValueAndValidity({ onlySelf: true });

          });
        }
      })
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }


  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls['password'].value) {
      return { confirm: true, error: true };
    }
    return {};
  };

  constructor(private fb: FormBuilder) {
    // this.init();
  }

  ngOnInit(): void {
    this.init();
  }

  init(): void {
    this.validateForm = this.fb.group({
      password: ['admin', [Validators.required]],
      username: ['admin', [Validators.required]],
      captcha: [123456, [Validators.required]]
    });
  }

}
